import Taro, { Component } from '@tarojs/taro'
import {View, Text, Form} from '@tarojs/components'
import {AtButton, AtIcon,AtInput} from 'taro-ui'
import { connect } from '@tarojs/redux'
import {
  asyncLoadCart,
  resetCart,
  asyncAddCartAction,
  asyncReduceCartAction,
  setUnpay,
  loadCart
} from '../../actions/cart'
import { asyncWechatCouponA } from '../../actions/reduction'
import { asyncLoadAddressList } from '../../actions/address'
import {asyncGetUserCoupoon, resetUserCoupon} from '../../actions/coupon'
import {asyncGetUserdVoucher, resetUserVoucher} from '../../actions/voucher'
import {asyncUserMoney} from '../../actions/user'
import './settle.styl'
import  CartGoodItem  from "../../components/cartGoodItem/index"
import { jumpUrl } from '../../utils/router'
import {
  asyncCreateOrder, // 创建普通订单
  asyncCreateGroupOrder // 创建拼团订单
} from '../../api/order'
import {queryShopMoney} from '../../api/user'


@connect(({ cart, address, coupon, user, shop, good,reduction,voucher }) => ({
  cart, address, coupon, user, shop, good,reduction,voucher
}), (dispatch) => ({
    // 加载系统满减
    onWechatCoupon () {
      dispatch(asyncWechatCouponA())
    },
  // 加载购物车数据
  onAsyncLoadCart () {
    return dispatch(asyncLoadCart())
  },
  // 重置购物车
  onResetCart () {
    dispatch(resetCart())
  },
  // 增加数量
  onAddCart (shop_id, product_id, product_num) {
    dispatch(asyncAddCartAction(shop_id, product_id, product_num))
  },
  // 减少数量
  onReduceCart (product_id, product_num) {
    dispatch(asyncReduceCartAction(product_id, product_num))
  },
  // 加载地址列表
  onLoadAddressList(shop_only = false) {
    dispatch(asyncLoadAddressList(shop_only))
  },
  // 加载优惠券
  onAsyncUserCoupon (shop_only = false) {
    dispatch(asyncGetUserCoupoon(shop_only))
  },
   // 加载代金券
   onAsyncUserVoucher (shop_only = true) {
    dispatch(asyncGetUserdVoucher(shop_only))
  },
  // 重置
  onResetUserCoupon () {
    dispatch(resetUserCoupon())
  },
  // 重置代金
  onResetUserVoucher () {
    dispatch(resetUserVoucher())
  },
  // 设置待支付订单
  onSetUnpay (data) {
    dispatch(setUnpay(data))
  },
  // 为结算设置配送方式
  onSetDeliveryMethod (method) {
    dispatch(loadCart({deliveryMethod: method}))
  },
  // 加载用户余额
  onAsyncUserMoney () {
    dispatch(asyncUserMoney())
  }
}))
class Settle extends Component {
  constructor () {
    super(...arguments)
    this.state = this.initialStateA
  }
    config = {
    navigationBarTitleText: '购物车'
  }

  get initialStateA() {
    return {
      submit: false, // 正在提交中
      shop_money: 0, // 店铺余额
      nameval:'',//提取用户名
      phoneval:''//提取用户电话
    };
  }
  // 输入提取用户名
  handlNamevalChange (val) {
    this.setState({
      nameval: val
    })
  }
  // 输入提取用户电话
  handPhonevalChange (val) {
    this.setState({
      phoneval: val
    })
  }

  // 跳转
  jumpTo (url) {
    jumpUrl(url, {method: 'navigateTo'})
  }

  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
  }

  // 跳转到收货地址列表
  jumpToAddress () {
    Taro.navigateTo({url: `/pages/address/index?from=settle`}) // 表示来自结算页
  }
  // 跳转到优惠券列表
  jumpToCoupon () {
    // 总价
    const total = this.props.cart.list
      .filter(product => product.selected === true)
      .reduce((sum, product) => sum + product.product_num * product.product.sale_price, 0)
    Taro.navigateTo({url: `/pages/coupon/index?from=settle&amount=${total}`}) // 表示来自结算页
  }
    // 跳转到代金券列表
    jumpToVoucher () {
      // 总价
      const total =this.state.total
      //   .filter(product => product.selected === true)
      //   .reduce((sum, product) => sum + product.product_num * product.product.sale_price, 0)
      Taro.navigateTo({url: `/pages/voucher/index?from=settle&amount=${total}`}) // 表示来自结算页
    }
 

  // 切换配送方式
  toggleDelivery () {
    const type_id = this.$router.params.type || 1
    Taro.showActionSheet({
      itemList: type_id === '2' ? ['成团后一小时达', '成团后到店自提'] : ['一小时达', '到店自提']
    }).then(({tapIndex}) => {
      switch (tapIndex) {
        case 0: // 店家配送
          this.props.onSetDeliveryMethod('shop')
          break
        case 1: // 到店自取
          this.props.onSetDeliveryMethod('user')
          break
      }
    })
  }

  // 获取用户店铺余额
  queryShopMoneyF () {
    const {token} = this.props.user
    const {shop_id} = this.props.shop
    queryShopMoney(token, shop_id).then(({data}) => {
      this.setState({
        shop_money: data
      })
    })
  }
  // 创建订单
  createOrder (total, real_total, computed_shop_money, select_coupon, select_voucher, address_id, shipping_fee,event) {
    const { name, price, thumb, id, group } = this.props.good
    if (this.state.submit) return
    this.setState({submit: true})
    const {token} = this.props.user
    const {nameval, phoneval} = this.state
    const {shop_id} = this.props.shop
    let {list, deliveryMethod} = this.props.cart
    let typeValueA =this.$router.params.type 
    if(typeValueA ==2 || typeValueA==3){
      deliveryMethod = "user"
      if (!nameval) {
        Taro.showToast({
          title: '请填写姓名',
          icon: 'none'
        })
        this.setState({submit: false})
        return
      }
      if (!phoneval) {
        Taro.showToast({
          title: '请填写手机号',
          icon: 'none'
        })
        this.setState({submit: false})
        return
      }
    }

    // 类型id 1 普通订单(每日鲜果) 2拼团订单 默认为 1  type 3 拼购商品单独结算
    const type_id = this.$router.params.type || 1
    const num = this.$router.params.num || 1
    // 如果用户选择的是快递，那么这里要验证是否选了地址
    if (deliveryMethod === 'shop' && !address_id) {
      Taro.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return
    }
    // 对商品列表做一次简单的处理
    const products = list
      .filter(product => product.selected === true)
      .map(product => {
        return {
          product_id: product.product_id,
          product_thumb: product.product.thumb,
          product_name: product.product.name,
          product_num: product.product_num,
          product_price: product.product.sale_price,

          total_price: product.product.sale_price * product.product_num
        }
      })
    // 基于商品列表 提取创建订单所需的商品信息
    let order_products = products
      .map(product => {
        return {
          product_id: product.product_id, // 物品id
          product_thumb: product.product_thumb, // 物品封面
          product_name: product.product_name, // 物品名称
          product_num: product.product_num, // 物品数量
          product_price: product.sale_price, // 物品单价
          total_price: product.total_price // 物品总价
        }
      })
    // 如果是 拼购商品的拼购结算
    if (type_id === '2') {
      order_products = {
        product_id: id, // 物品id
        product_thumb: thumb, // 物品封面
        product_name: name, // 物品名称
        product_num: num, // 物品数量
        product_price: parseInt(group.group_price, 10), // 物品单价
        total_price: parseInt(group.group_price, 10) * num // 物品总价
      }
    }
    // 如果是 拼购商品的普通结算
    if (type_id === '3') {
      order_products = [{
        product_id: id, // 物品id
        product_thumb: thumb, // 物品封面
        product_name: name, // 物品名称
        product_num: num, // 物品数量
        product_price: price, // 物品单价
        total_price: price * num // 物品总价
      }]
    }
    // 创建订单
    if (type_id === '2') {
      // type_id === '2' 创建拼团订单
      asyncCreateGroupOrder({
        token,
        type_id: 2, // 类型id
        shop_id, // 店铺id
        total_money: real_total, // 订单实付金额，以分为单位
        total_amount: total, // 订单总额
        user_money: computed_shop_money, // 余额支付部分
        product: order_products, // 订单物品
        user_coupon_id: select_coupon && select_coupon.id,  //优惠券id,为空表示没有使用优惠券
        user_voucher_id: select_voucher && select_voucher.id,  //优惠券id,为空表示没有使用优惠券
        address_id: deliveryMethod === 'shop' ? address_id : null, // 收货地址id 为空表示到店自取
        shipping_fee: deliveryMethod === 'shop' ? shipping_fee : 0, // 收货地址id 为空表示到店自取,运费
        form_id: event.detail.formId,
        name:nameval,
        phone:phoneval
      }).then(({status,data}) => {
        if (status) {
          if(data==true){
            Taro.redirectTo({url: `/pages/order/index?from=settle&tab=0`}) // 表示来自结算页
          }else{
            let params ={
              timeStamp:data.timeStamp.toString(),
              nonceStr:data.nonceStr,
              package:data.package,
              signType:data.signType,
              paySign:data.paySign,
            }
            Taro.requestPayment(params).then((res)=>{
              if(res.errMsg=='requestPayment:ok'){
                Taro.redirectTo({url: `/pages/order/index?from=settle&tab=0`}) // 表示来自结算页
              }else{
                throw '支付遇到问题请联系客服!'
              }
            })
          }
          // 列表购买
          // Taro.redirectTo({url: `/pages/order/index?from=settle&tab=0`}) // 表示来自结算页
          // console.log("666666666")

        } else {
          throw '订单创建失败!'
        }
      }).catch(e => {
        console.error(e)
      })
    } else {
      //  type_id === '3' 是单独购买拼团商品 route中没有type时表明这是一个普通订单
      asyncCreateOrder({
        token,
        type_id: 1, // 类型id
        shop_id, // 店铺id
        total_money: real_total, // 订单实付金额，以分为单位
        total_amount: total, // 订单总额
        user_money: computed_shop_money, // 余额支付部分
        products: order_products, // 订单物品
        user_coupon_id: select_coupon && select_coupon.id,  //优惠券id,为空表示没有使用优惠券
        user_voucher_id: select_voucher && select_voucher.id,  //优惠券id,为空表示没有使用优惠券
        address_id: deliveryMethod === 'shop' ? address_id : null, // 收货地址id 为空表示到店自取
        shipping_fee: deliveryMethod === 'shop' ? shipping_fee : 0, // 收货地址id 为空表示到店自取,运费
        form_id: event.detail.formId,
        name:nameval,
        phone:phoneval
      }).then(({status,data}) => {
        if (status) {
          if(data==true){
            Taro.redirectTo({url: `/pages/order/index?from=settle&tab=0`}) // 表示来自结算页
          }else{
            let params ={
              timeStamp:data.timeStamp.toString(),
              nonceStr:data.nonceStr,
              package:data.package,
              signType:data.signType,
              paySign:data.paySign,
            }
            Taro.requestPayment(params).then((res)=>{
              if(res.errMsg=='requestPayment:ok'){
                Taro.redirectTo({url: `/pages/order/index?from=settle&tab=0`}) // 表示来自结算页
              }else{
                throw '支付遇到问题请联系客服!'
              }
            })
          }
          // 列表购买
          // Taro.redirectTo({url: `/pages/order/index?from=settle&tab=0`}) // 表示来自结算页

        } else {
          throw '订单创建失败!'
        }
      }).catch(e => {
        console.error(e)
      })
    }
  }

  componentWillReceiveProps () {
    // console.log(this.props, nextProps)
  }
  componentDidMount () {
  }
  componentWillUnmount () { }

  componentDidShow () {
    // 加载地址列表
    this.props.onLoadAddressList(true)
    // 重置优惠券
    this.props.onResetUserCoupon()
    // 重置代金
    this.props.onResetUserVoucher()
    // 加载优惠券列表
    this.props.onAsyncUserCoupon(true)
     // 加载代金列表
     this.props.onAsyncUserVoucher(true)
    // 加载用户余额
    this.props.onAsyncUserMoney()
    // 加载用户店铺余额
    this.queryShopMoneyF()
  }

  componentDidHide () {
    this.setState({
      submit: false, // 正在提交中
    })
  }

  render () {
    // type 1 普通购物车结算，type 2 拼购商品, type 3 拼购商品单独结算
    console.log(this.$router.params)
    const {type, num} = this.$router.params
    
    // 从拼购商品详情过来的话
    const { goodId, name, price, tags, thumb, group,weight,spec_name,sale_price } = this.props.good
    let {shop_money,nameval,phoneval} = this.state // 店铺余额
    if(this.props.user.name){
      nameval=this.props.user.name
    }
    if(this.props.user.phone){
      phoneval=this.props.user.phone
    }
    // 处理收货地址
    const { addressList, select_id } = this.props.address
    const noneAddress = addressList.length === 0 // 表示是否有收货地址
    let defaultAddress = addressList.find(address => address.is_default === '1') // 默认地址
    let selectAddress = addressList.find(address => address.id === select_id) // 用户选中id
    if (!defaultAddress && !noneAddress) { // 如果有地址却没有默认，选第一个
      defaultAddress = addressList[0]
    }
    if (!selectAddress && defaultAddress) { // 如果没有选中，但有默认
      selectAddress = defaultAddress
    }
    // 以上是对地址的处理

    // 对购物车物品 配送方式的处理
    let {list, deliveryMethod} = this.props.cart
    let typeValue =this.$router.params.type 
    if(typeValue ==2 || typeValue==3){
      deliveryMethod = "user"
    }

    
    // 总价
    let total
    if (type === '1') {
      total = list
        .filter(product => product.selected === true)
        .reduce((sum, product) => sum + product.product_num * product.product.sale_price, 0)
    } else if (type === '2') {
      // 拼购商品拼购购买
      total = parseInt(group.group_price, 10) * num
    } else if (type === '3') {
      // 拼购商品普通购买
      total = sale_price * num
    }

    // 购物车过来的 商品列表
    let renderList = list
      .filter(product => product.selected === true)
      .map((item, index) => {
        return (
          <CartGoodItem
            goodId={item.product_id}
            shop_id={item.shop_id}
            key={index}
            tags={item.product.tags}
            thumb={item.product.thumb}
            name={item.product.name}
            sales={item.product.month_sale}
            price={item.product.sale_price}
            sale_price={item.product.sale_price}
            weight={item.product.weight}
            disable
            original_price={item.product.original_price}
            product_num={parseInt(item.product_num)}
            spec_name={item.product.spec.name}
          />
        )
      })
    console.log(total)
    // 运费
    const {shipping_fee} = this.props.shop
    // 处理优惠券
    const {select_coupon_id, list: coupon_ist} = this.props.coupon
    const canUsedCoupon = coupon_ist.filter(coupon => coupon.coupon.min_amount * 100 <= total)  // 可用券的数量
    const select_coupon = select_coupon_id ? canUsedCoupon.find(coupon => coupon.id == select_coupon_id) : null
    // 处理总价减去优惠券金额
    let real_total = total
    if (select_coupon) {
      real_total = (total - select_coupon.coupon.value * 100)
      if (real_total < 0) real_total = 0
    }

      // 处理代金券
    const {select_voucher_id,  data: listVoucher} = this.props.voucher
    const canUsedVoucher = listVoucher.filter(coupon => coupon.value * 100 <= total)  // 可用券的数量
    const select_voucher = select_voucher_id ? canUsedVoucher.find(coupon => coupon.id == select_voucher_id) : null
    console.log(select_voucher_id)

    if (select_voucher) {
      real_total = (total - select_voucher.value * 100)
      if (real_total < 0) real_total = 0
    }

    // 处理 real_total 再减去余额后的实际支付金额
    let final_total = total
    let computed_shop_money = shop_money || 0
    if (computed_shop_money > real_total) {
      computed_shop_money = real_total
    }
    final_total = real_total - computed_shop_money
    if(shipping_fee>0 && deliveryMethod === 'shop'){
      final_total = final_total + shipping_fee
    }

    //加载系统满减
    const {data} = this.props.reduction
    // let MaxNum =Math.max.apply(Math, data.map(function(o) {return o.full}))
    // let MinNum =Math.min.apply(Math, data.map(function(o) {return o.full}))
    const handle = (property) => {
      return function(a,b){
          const val1 = a[property];
          const val2 = b[property];
          return val1 - val2;
      }
    }

  data.sort(handle('full'));
    let kvalue = '';
    for (let i = 0; i < data.length; i++) {
      // console.log(final_total/100,data[0].full, data[data.length - 1].full,data[i].full,'5555555') 
      if (final_total/100 < data[0].full) {
        kvalue = '';
        break;
      }
      if (final_total/100 >= data[data.length - 1].full) {
        final_total = final_total - data[data.length - 1].reduce* 100
        kvalue ='系统促销优惠 : ' + data[data.length - 1].name;
        break;
      }
      if (final_total/100 >= data[i].full && final_total/100 < data[i + 1].full) {
        final_total = final_total - data[i].reduce* 100;
        kvalue ='系统促销优惠 : ' + data[i].name;
        break;
      }
    }

 
    // console.log(kvalue) 
    // console.log(MinNum)
    
    
    return (
      <View className='settle'>
        <Form reportSubmit onSubmit={this.createOrder.bind(this, total, final_total, computed_shop_money, select_coupon, select_voucher, selectAddress && selectAddress.id,shipping_fee)}>

        {/*收货地址 如果用户选的自取，这里不必展示*/}
        { deliveryMethod === 'shop' && <View className='address' onClick={this.jumpToAddress.bind(this)}>
          {!selectAddress && <View className='left'>
            <View className='main'>请选择收货地址</View>
          </View>}
          {selectAddress && <View className='left'>
            <View className='attach'>{selectAddress.address}</View>
            <View className='main'>{selectAddress.village}</View>
            <View className='attach'>{selectAddress.truename + selectAddress.gender + '    '}{selectAddress.phone}</View>
          </View>}
          <View className='right'>
            <AtIcon value='chevron-right' size='20' color='#333333' />
          </View>
        </View>}

        {/*配送方式*/}
        <View className='delivery'>
          <View className='left'>
            <View className='bar' />
            <View className='method'> {deliveryMethod === 'shop' ? '1小时达' : '到店自取'}</View>
          </View>
          <View className='right' onClick={this.toggleDelivery.bind(this)}>
            {/*拼购*/}
            {type === '2'  && <Text>{deliveryMethod === 'shop' ? '成团后一小时达' : '成团后到店自提'} </Text>}
            {/*非拼购*/}
            {type !== '2'  && <Text>{deliveryMethod === 'shop' ? '今天1小时内送达[可选]' : '到店自取'} </Text>}

            <AtIcon value='chevron-right' size='12' color='#FD7474' />
          </View>
        </View>

        {/* 商品列表 */}
        <View>
          {/*购物车过来的的商品列表*/}
          {type === '1' && <View>{renderList}</View>}
          {/*拼购商品过来的商品详情(拼购购买)*/}
          {type === '2' && <CartGoodItem
            goodId={goodId}
            shop_id=''
            tags={tags}
            thumb={thumb}
            name={name}
            weight={weight}
            spec_name={spec_name}
            sales='0'
            price={parseInt(group.group_price, 10)}
            disable
            product_num={parseInt(num)}
          />}
          {/*拼购商品过来的商品详情(直接购买)*/}
          {type === '3' && <CartGoodItem
            goodId={goodId}
            shop_id=''
            tags={tags}
            thumb={thumb}
            name={name}
            weight={weight}
            spec_name={spec_name}
            sales='0'
            price={sale_price}
            disable
            product_num={parseInt(num)}
          />}
        </View>
        {/*系统促销优惠*/}
        { type != '2'  && type != '3' && <View className='cuxiao'>{kvalue}</View>}
        <View className='coupon'>
          <View className='item'>
            <View className='left'>商品总价</View>
            <View className='right'>￥{parseFloat(total / 100).toFixed(2)}</View>
          </View>

          {/*优惠券*/}
          {select_coupon &&<View onClick={this.jumpToCoupon.bind(this)} className='item'>
            <View className='left'>
              <Text className='small'>优惠券</Text>
            </View>
            <View className='right coupon-right'>
              {select_coupon && <Text>-{parseFloat(select_coupon.coupon.value).toFixed(2)}</Text>}
              {!select_coupon && <Text>{canUsedCoupon.length > 0  ? `${canUsedCoupon.length} 优惠券可用` : '无可用优惠券'}</Text>}
              <AtIcon value='chevron-right' size='12' color='#B2B2B2' />
            </View>
          </View>}
          {/*代金券 */}
          { type != '2'  && type != '3'&& <View onClick={this.jumpToVoucher.bind(this)} className='item'>
            <View className='left'>
              <Text className='small'>代金券</Text>
            </View>
            <View className='right coupon-right'>
              {/* {!select_voucher && <Text> 无可用代金券</Text>}
              <AtIcon value='chevron-right' size='12' color='#B2B2B2' /> */}
              {select_voucher && <Text>-{parseFloat(select_voucher.value).toFixed(2)}</Text>}
              {!select_voucher && <Text>{canUsedVoucher.length > 0  ? `${canUsedVoucher.length} 代金券可用` : '无可用代金券'}</Text>}
              <AtIcon value='chevron-right' size='12' color='#B2B2B2' />
            </View>
          </View>}
         
          {/*配送费*/}
          {deliveryMethod === 'shop' &&<View  className='item'>
            <View className='left'>
              <Text className='small'>配送费</Text>
            </View>
            <View className='right'>
              <Text>￥{parseFloat(shipping_fee / 100).toFixed(2)}</Text>
              {/* <AtIcon value='chevron-right' size='12' color='#B2B2B2' /> */}
            </View>
          </View>}

          {/*红包金*/}
          <View className='item'>
            <View className='left'>
              <Text className='small'>可用余额</Text>
            </View>
            <View className='right'>
              <Text>￥{parseFloat(computed_shop_money / 100).toFixed(2)}</Text>
            </View>
          </View>

          <View className='item'>
            <View className='left small'>商品应付</View>
            <View className='right'>￥{parseFloat(final_total / 100).toFixed(2)}</View>
          </View>
          {deliveryMethod != 'shop' &&<View className='users_item bott'>
            <AtInput
              className='small_usersname'
              name='nameval' 
              title='提货人姓名'
              type='text'
              value={nameval}
              onChange={this.handlNamevalChange.bind(this)}
            />
          </View>}
          {deliveryMethod != 'shop' &&<View className='users_item'>
            <AtInput
              className='small_usersname'
              name='phoneval' 
              title='手机号'
              type='phone'
              value={phoneval}
              // placeholder='请填写手机号'
              onChange={this.handPhonevalChange.bind(this)}
            />
          </View>}
        </View>
        {/*底部*/}
        <View className='footer'>
          <View className='info'>
            <View className='sum'>
              <View className='amount'>
                <Text className='amount-label'>合计：</Text>
                <Text className='amount-value'>￥{parseFloat(final_total / 100).toFixed(2)}</Text>
              </View>
              {/* <Text className='reight'>免配送费</Text> */}
            </View>
          </View>
          <AtButton className='checkout' formType='submit'><Text>提交订单</Text> </AtButton>
        </View>
        </Form>
      </View>
      
      
    )
  }
}

export default Settle
